<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { qrcodeApi, categoryApi } from '../api'
import QRCode from 'qrcode'

const router = useRouter()

// 表单数据
const formData = reactive({
  content: '',
  title: '',
  description: '',
  categoryId: ''
})

// 分类列表
const categories = ref([])
// 二维码图片URL
const qrImageUrl = ref('')
// 加载状态
const loading = ref(false)
// 保存状态
const saving = ref(false)
// 错误信息
const errorMsg = ref('')
// 分类加载状态
const categoriesLoading = ref(false)

// 生成二维码
const generateQR = async () => {
  if (!formData.content) {
    errorMsg.value = '请输入二维码内容'
    return
  }
  
  errorMsg.value = ''
  loading.value = true
  qrImageUrl.value = ''
  
  try {
    // 生成二维码
    const url = await QRCode.toDataURL(formData.content, {
      width: 300,
      margin: 2,
      color: {
        dark: '#000000',
        light: '#ffffff'
      }
    })
    qrImageUrl.value = url
  } catch (error) {
    console.error('生成二维码出错:', error)
    errorMsg.value = '生成二维码失败，请重试'
  } finally {
    loading.value = false
  }
}

// 保存二维码
const saveQRCode = async () => {
  if (!formData.content) {
    errorMsg.value = '请输入二维码内容'
    return
  }
  
  if (!qrImageUrl.value) {
    errorMsg.value = '请先生成二维码'
    return
  }
  
  if (!formData.title) {
    errorMsg.value = '请输入二维码标题'
    return
  }
  
  errorMsg.value = ''
  saving.value = true
  
  try {
    // 创建二维码记录
    const createRes = await qrcodeApi.createQRCode({
      content: formData.content,
      title: formData.title,
      description: formData.description,
      categoryId: formData.categoryId || null
    })
    
    // 保存二维码图片
    await qrcodeApi.saveQRCodeImage(createRes.data.id, qrImageUrl.value)
    
    // 保存成功，跳转到二维码列表页
    router.push('/dashboard/qrcode')
  } catch (error) {
    console.error('保存二维码出错:', error)
    errorMsg.value = '保存二维码失败: ' + (error.message || '未知错误')
  } finally {
    saving.value = false
  }
}

// 获取分类列表
const fetchCategories = async () => {
  try {
    categoriesLoading.value = true
    const response = await categoryApi.getCategories()
    categories.value = response.data.list || []
  } catch (error) {
    console.error('获取分类列表失败:', error)
    // 如果获取分类失败，不影响主要功能
  } finally {
    categoriesLoading.value = false
  }
}

// 取消创建
const cancelCreate = () => {
  router.push('/dashboard/qrcode')
}

// 组件挂载时获取分类列表
onMounted(() => {
  fetchCategories()
})
</script>

<template>
  <div class="qrcode-create">
    <div class="page-header">
      <h2>创建二维码</h2>
      <button @click="cancelCreate" class="cancel-btn">取消</button>
    </div>
    
    <!-- 错误提示 -->
    <div v-if="errorMsg" class="error-message">
      {{ errorMsg }}
    </div>
    
    <div class="create-content">
      <!-- 表单区域 -->
      <div class="form-section">
        <form @submit.prevent="generateQR">
          <div class="form-group">
            <label for="content">二维码内容 <span class="required">*</span></label>
            <textarea 
              id="content" 
              v-model="formData.content" 
              placeholder="请输入要生成二维码的内容，如网址、文本等"
              rows="4"
              required
            ></textarea>
          </div>
          
          <div class="form-group">
            <label for="title">标题 <span class="required">*</span></label>
            <input 
              type="text" 
              id="title" 
              v-model="formData.title" 
              placeholder="请输入二维码标题"
              required
            >
          </div>
          
          <div class="form-group">
            <label for="description">描述</label>
            <textarea 
              id="description" 
              v-model="formData.description" 
              placeholder="请输入二维码描述（选填）"
              rows="3"
            ></textarea>
          </div>
          
          <div class="form-group">
            <label for="category">分类</label>
            <select 
              id="category" 
              v-model="formData.categoryId" 
              :disabled="categoriesLoading"
            >
              <option value="">请选择分类（选填）</option>
              <option 
                v-for="category in categories" 
                :key="category.id" 
                :value="category.id"
              >
                {{ category.name }}
              </option>
            </select>
          </div>
          
          <div class="form-actions">
            <button type="submit" :disabled="loading" class="generate-btn">
              {{ loading ? '生成中...' : '生成二维码' }}
            </button>
          </div>
        </form>
      </div>
      
      <!-- 预览区域 -->
      <div class="preview-section">
        <h3>二维码预览</h3>
        
        <div class="qr-preview">
          <div v-if="loading" class="loading-spinner">
            <div class="spinner"></div>
            <p>生成中...</p>
          </div>
          <img v-else-if="qrImageUrl" :src="qrImageUrl" alt="生成的二维码" class="qr-image" />
          <div v-else class="empty-preview">
            <p>请输入内容并点击生成按钮</p>
          </div>
        </div>
        
        <button 
          v-if="qrImageUrl" 
          @click="saveQRCode" 
          :disabled="saving" 
          class="save-btn"
        >
          {{ saving ? '保存中...' : '保存二维码' }}
        </button>
      </div>
    </div>
  </div>
</template>

<style scoped>
.qrcode-create {
  background: var(--card-bg);
  border-radius: var(--border-radius-lg);
  box-shadow: var(--shadow-lg);
  padding: var(--spacing-xl);
  margin: var(--spacing-md);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: var(--spacing-xl);
  padding-bottom: var(--spacing-lg);
  border-bottom: 2px solid var(--border-color);
  position: relative;
}

.page-header::after {
  content: '';
  position: absolute;
  bottom: -2px;
  left: 0;
  width: 80px;
  height: 2px;
  background: var(--gradient-primary);
  border-radius: 1px;
}

h2 {
  margin: 0;
  color: var(--dark-color);
  font-weight: 700;
  font-size: 1.8rem;
  background: var(--gradient-primary);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.cancel-btn {
  background: var(--bg-light);
  color: var(--text-secondary);
  border: 2px solid var(--border-color);
  padding: var(--spacing-sm) var(--spacing-lg);
  border-radius: var(--border-radius-md);
  cursor: pointer;
  font-weight: 600;
  transition: all 0.3s ease;
  box-shadow: var(--shadow-sm);
}

.cancel-btn:hover {
  background: var(--danger-light);
  color: var(--danger-color);
  border-color: var(--danger-color);
  transform: translateY(-2px);
  box-shadow: var(--shadow-md);
}

.error-message {
  background: linear-gradient(135deg, #ffebee 0%, #ffcdd2 100%);
  color: var(--danger-color);
  padding: var(--spacing-md);
  border-radius: var(--border-radius-md);
  margin-bottom: var(--spacing-lg);
  border-left: 4px solid var(--danger-color);
  box-shadow: var(--shadow-sm);
  font-weight: 500;
}

.create-content {
  display: flex;
  gap: var(--spacing-xxl);
  align-items: flex-start;
}

@media (max-width: 768px) {
  .create-content {
    flex-direction: column;
    gap: var(--spacing-xl);
  }
}

.form-section {
  flex: 1;
  background: var(--card-bg);
  padding: var(--spacing-xl);
  border-radius: var(--border-radius-lg);
  box-shadow: var(--shadow-md);
  border: 1px solid var(--border-color);
}

.preview-section {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  background: var(--card-bg);
  padding: var(--spacing-xl);
  border-radius: var(--border-radius-lg);
  box-shadow: var(--shadow-md);
  border: 1px solid var(--border-color);
}

.form-group {
  margin-bottom: var(--spacing-lg);
}

label {
  display: block;
  margin-bottom: var(--spacing-sm);
  font-weight: 600;
  color: var(--dark-color);
  font-size: 0.95rem;
}

.required {
  color: var(--danger-color);
  font-weight: 700;
}

input, textarea, select {
  width: 100%;
  padding: var(--spacing-md);
  border: 2px solid var(--border-color);
  border-radius: var(--border-radius-md);
  font-size: 1rem;
  font-family: var(--font-family);
  transition: all 0.3s ease;
  background: var(--bg-light);
  color: var(--dark-color);
  box-sizing: border-box;
}

input:focus, textarea:focus, select:focus {
  border-color: var(--primary-color);
  outline: none;
  box-shadow: 0 0 0 3px rgba(var(--primary-rgb), 0.1);
  background: white;
  transform: translateY(-1px);
}

input::placeholder, textarea::placeholder {
  color: var(--text-muted);
  font-style: italic;
}

select:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

select option {
  padding: var(--spacing-sm);
  background: white;
  color: var(--dark-color);
}

.form-actions {
  margin-top: var(--spacing-xl);
}

button {
  padding: var(--spacing-md) var(--spacing-lg);
  border: none;
  border-radius: var(--border-radius-md);
  font-size: 1rem;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
  box-shadow: var(--shadow-md);
}

button::before {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, transparent, rgba(255,255,255,0.3), transparent);
  transition: left 0.5s;
}

button:hover:not(:disabled)::before {
  left: 100%;
}

button:disabled {
  opacity: 0.6;
  cursor: not-allowed;
  transform: none;
}

.generate-btn {
  background: var(--gradient-primary);
  color: white;
  width: 100%;
}

.generate-btn:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: var(--shadow-lg);
}

h3 {
  margin-top: 0;
  margin-bottom: var(--spacing-lg);
  color: var(--dark-color);
  text-align: center;
  font-weight: 700;
  font-size: 1.4rem;
  background: var(--gradient-primary);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.qr-preview {
  width: 320px;
  height: 320px;
  border: 2px solid var(--border-color);
  border-radius: var(--border-radius-lg);
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: var(--spacing-xl);
  background: linear-gradient(135deg, #f8fafc 0%, #e2e8f0 100%);
  position: relative;
  overflow: hidden;
  box-shadow: var(--shadow-md);
}

.qr-preview::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"><defs><pattern id="grid" width="10" height="10" patternUnits="userSpaceOnUse"><path d="M 10 0 L 0 0 0 10" fill="none" stroke="%23e2e8f0" stroke-width="0.5"/></pattern></defs><rect width="100" height="100" fill="url(%23grid)"/></svg>');
  opacity: 0.3;
}

.qr-image {
  max-width: 90%;
  max-height: 90%;
  border-radius: var(--border-radius-md);
  box-shadow: var(--shadow-lg);
  position: relative;
  z-index: 1;
  transition: transform 0.3s ease;
}

.qr-image:hover {
  transform: scale(1.05);
}

.empty-preview {
  color: var(--text-secondary);
  text-align: center;
  font-weight: 500;
  position: relative;
  z-index: 1;
}

.empty-preview::before {
  content: '📱';
  font-size: 3rem;
  display: block;
  margin-bottom: var(--spacing-md);
  opacity: 0.5;
}

.loading-spinner {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  position: relative;
  z-index: 1;
}

.spinner {
  width: 50px;
  height: 50px;
  border: 4px solid rgba(var(--primary-rgb), 0.1);
  border-radius: 50%;
  border-top-color: var(--primary-color);
  animation: spin 1s ease-in-out infinite;
  margin-bottom: var(--spacing-md);
}

@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}

.loading-spinner p {
  color: var(--text-secondary);
  font-weight: 500;
  margin: 0;
}

.save-btn {
  background: linear-gradient(135deg, #3b82f6 0%, #1d4ed8 100%);
  color: white;
  width: 220px;
  font-size: 1.1rem;
}

.save-btn:hover:not(:disabled) {
  transform: translateY(-3px);
  box-shadow: var(--shadow-xl);
}
</style>